<template>
  <div class="bg-color-black" :class="{ fullscreen: isFullscreen }">
    <!-- 全屏按钮，放在右上角 -->
    <button class="fullscreen-btn" @click="toggleFullscreen">
      <span v-if="!isFullscreen">⛶</span>
      <span v-else>⨉</span>
    </button>
    <!-- 通过 :key 来强制重新挂载 -->
    <div id="chart-container" :key="chartKey"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {mapActions} from "vuex";

export default {
  name: 'CenterLeft2Chart',
  data() {
    return {
      isFullscreen: false,
      chart: null,
      chartKey: 0,
      userId: null,
      graphData: null
    };
  },
  mounted() {
    this.loadData();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    ...mapActions({
      getProjectGraphData: 'getProjectGraphDataInTen'
    }),
    async loadData() {
      this.userId = this.$store.state.user.userInfo.id;
      this.graphData = await this.getProjectGraphData(this.userId);
      this.initChart();
    },
    transformData() {
      if (!this.graphData || !this.graphData.nodes || !this.graphData.links) {
        return { nodes: [], links: [] }
      }
      const nodes = this.graphData.nodes.map(n => {
        // 获取风险数值（转为数字，默认 0，避免非数字报错）
        const riskValue = Number(n.properties?.["风险数值"]) || 0;

        // 步骤2：按风险数值划分等级，绑定对应颜色（可调整阈值和颜色）
        let nodeColor;
        if (riskValue < 0.333) {
          nodeColor = '#43BC86';
        } else if (riskValue < 0.667) {
          nodeColor = '#F9844A';
        } else {
          nodeColor = '#F94144';
        }
        return {
          id: n.id.toString(),
          name: n.name,
          category: n.group,
          // symbolSize: 30 + Math.pow(riskValue, 0.5) * 60,
          symbolSize: 60,
          value: riskValue,
          color: nodeColor
        };
      });

      const links = this.graphData.links.map(r => ({
        source: r.source.toString(),
        target: r.target.toString(),
        name: r.name
      }));

      return { nodes, links };
    },

    //在 ECharts 配置中应用节点颜色，优化 Tooltip
    initChart() {
      const chartDom = document.getElementById('chart-container');
      if (!chartDom) return;

      this.chart = echarts.init(chartDom);
      this.chart.showLoading();

      const graph = this.transformData();
      this.chart.hideLoading();

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            if (params.dataType === 'edge') {
              return `关系: ${params.data.name}`;
            }
            let riskLevel;
            if (params.data.value < 0.333) riskLevel = '低风险';
            else if (params.data.value < 0.667) riskLevel = '中风险';
            else riskLevel = '高风险';
            return `${params.name}<br>风险数值: ${params.data.value.toFixed(3)}<br>风险等级: ${riskLevel}`;
          }
        },
        series: [
          {
            type: 'graph',
            layout: 'circular',
            data: graph.nodes,
            links: graph.links,
            roam: true,
            label: {
              show: true,
              color: '#fff',
              fontSize: 16,
            },
            itemStyle: {
              color: function(params) {
                return params.data.color;
              },
            },
            lineStyle: {
              color: '#aaa',
              curveness: 0.3
            },
            edgeSymbol: ['none', 'arrow'],
            edgeSymbolSize: [0, 8],
            edgeLabel: {
              show: true,
              formatter: function (params) {
                return params.data.name;
              },
              fontSize: 15,
              color: '#fff',
              backgroundColor: 'rgba(0, 0, 0, 0.5)',
              padding: [2, 5],
              borderRadius: 2
            },
          }
        ]
      };
      this.chart.setOption(option);
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    toggleFullscreen() {
      this.isFullscreen = !this.isFullscreen;
      this.chartKey += 1;
      this.$nextTick(() => {
        if (this.chart) {
          this.chart.dispose();
          this.chart = null;
        }
        this.initChart();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
$box-height: 400px;
$box-width: 510px;

#chart-container {
  padding: 16px;
  padding-top: 20px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;
}

.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background-color: #020138;
  display: flex;
  justify-content: center;
  align-items: center;
}

.fullscreen #chart-container {
  width: 100%;
  height: 100%;
  padding: 0;
  border-radius: 0;
}

.fullscreen-btn {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #ccc;
  padding: 3px 5px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 16px;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10000;
}
</style>
